package com.example.demo.controller;

import com.example.demo.common.Func;
import com.example.demo.exception.BusinessException;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/download")
@Api(tags = "20、下载管理")
@ApiSupport(author = "罗海林", order = 20)
@Validated
public class DownloadController {

    @GetMapping("/attachment")
    @ApiOperation(value = "以附件下载（一次性读取到内存）")
    @ApiOperationSupport(author = "罗海林", order = 1)
    public void attachment(HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        InputStream fis = null;
        byte[] buffer = null;
        OutputStream outputStream = null;

        try {
            String path = Func.getRootPath() + "/file/download/excel/demo.xlsx";
            File file = new File(path);
            String filename = file.getName();

            // 将文件写入输入流
            fileInputStream = new FileInputStream(file);
            fis = new BufferedInputStream(fileInputStream);
            buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            // Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            // attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // inline方式时ContentType需明确具体类型，如image/jpeg、application/pdf
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            //response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();

            outputStream.close();
            buffer.clone();
            fileInputStream.close();
        }
        catch (Exception ex) {
            if (outputStream != null) {
                try {
                    outputStream.close();
                }
                catch (Exception ignored) { }
            }
            if (fis != null) {
                try {
                    fis.close();
                }
                catch (Exception ignored) { }
            }
            if (buffer != null) {
                buffer.clone();
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }
                catch (Exception ignored) { }
            }

            throw new BusinessException("文件下载失败");
        }
    }

    @GetMapping("/loop")
    @ApiOperation(value = "以附件下载（循环读取到内存）")
    @ApiOperationSupport(author = "罗海林", order = 2)
    public void loop(HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        byte[] buffer = null;
        ServletOutputStream outputStream = null;

        try {
            String path = Func.getRootPath() + "/file/template/template.xlsx";
            File file = new File(path);
            String filename = file.getName();

            // 将文件写入输入流
            fileInputStream = new FileInputStream(file);

            // 清空response
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");

            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            outputStream = response.getOutputStream();
            buffer = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }

            outputStream.close();
            buffer.clone();
            fileInputStream.close();
        }
        catch (Exception ex) {
            if (outputStream != null) {
                try {
                    outputStream.close();
                }
                catch (Exception ignored) { }
            }
            if (buffer != null) {
                buffer.clone();
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                }
                catch (Exception ignored) { }
            }

            throw new BusinessException("文件下载失败");
        }
    }

}
